//
//  TimeTrackerIncomeDetailViewController.m
//  TimeTracker
//
//  Created by Michael Flakus on 1/7/13.
//  Copyright (c) 2013 Michael Flakus. All rights reserved.
//

#import "TaskDetailViewController.h"
#import <QuartzCore/QuartzCore.h>

@interface TaskDetailViewController ()

@end

@implementation TaskDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	self.title = @"Task Details";
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
	self.tableView.allowsSelectionDuringEditing = YES;
    
    NSLog(@"task id: %@",_taskDetailModel[0]);
    
}


- (void)viewWillAppear:(BOOL)animated {
	
	[super viewWillAppear:animated];
	
    
    NSLog(@"viewWillAppear.... reload data from db");
    
    
    _taskID = _taskDetailModel[0];
    _activityName = _taskDetailModel[1];
    _categoryName = _taskDetailModel[2];
    _startTimeString = _taskDetailModel[3];
    _endTimeString = _taskDetailModel[4];
    _notes = _taskDetailModel[5];
    
    
    // database lookups
    @try {
        
        // connect to db
        
        NSString *docsDir;
        NSArray *dirPaths;
        
        // Get the documents directory
        dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        
        docsDir = dirPaths[0];
        
        // Build the path to the database file
        _databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"TimeTracker.sqlite"]];
        
        NSFileManager *filemgr = [NSFileManager defaultManager];
        
        // check to see if database already exists...
        if ([filemgr fileExistsAtPath: _databasePath ] == YES)
        {
            // open database
            if(!(sqlite3_open([_databasePath UTF8String], &_database) == SQLITE_OK))
            {
                NSLog(@"An error has occured when trying to open the database");
            }
            
            // load task details
            NSString *select_task = [NSString stringWithFormat:@"SELECT tasklog.id,activities.activity_name,categories.name,tasklog.start_time,tasklog.end_time,tasklog.notes from tasklog,activities,categories where tasklog.activity_id = activities.id and categories.id = activities.category_id and tasklog.active = 1 and tasklog.id = %@",_taskDetailModel[0]];
            const char *select_task_const = [select_task UTF8String];
            
            sqlite3_stmt *res_task;
            if(sqlite3_prepare(_database, select_task_const, -1, &res_task, NULL) != SQLITE_OK)
            {
                NSLog(@"Problem with prepare statement: %s",select_task_const);
                NSLog(@"%s Prepare failure '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(_database), sqlite3_errcode(_database));
            }
            else
            {
                NSDateFormatter *dateFormatUI = [[NSDateFormatter alloc] init];
                [dateFormatUI setDateFormat:@"MM/dd/yyyy h:mma"];
                
                NSDateFormatter *dateFormatDB = [[NSDateFormatter alloc] init];
                [dateFormatDB setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

                
                while (sqlite3_step(res_task)==SQLITE_ROW) {
                    
                    NSLog(@"Found the task");
                    
                    _taskID = [NSString stringWithUTF8String:(char *) sqlite3_column_text(res_task,0)];
                    _activityName = [NSString stringWithUTF8String:(char *) sqlite3_column_text(res_task,1)];
                    _categoryName =[NSString stringWithUTF8String:(char *) sqlite3_column_text(res_task,2)];
                    _startTimeString = [NSString stringWithUTF8String:(char *) sqlite3_column_text(res_task,3)];
                    
                    // format start time
                    _startTime = [dateFormatDB dateFromString:_startTimeString];
                    _startTimeString = [dateFormatUI stringFromDate:_startTime];
                    
                    if(sqlite3_column_text(res_task,4) != NULL)
                    {
                        _endTimeString = [NSString stringWithUTF8String:(char *) sqlite3_column_text(res_task,4)];
                    
                        NSLog(@"end time before formatting: %@",_endTimeString);
                        // format end time
                        _endTime = [dateFormatDB dateFromString:_endTimeString];
                        _endTimeString = [dateFormatUI stringFromDate:_endTime];
                    }
                    
                    _notes = [NSString stringWithUTF8String:(char *) sqlite3_column_text(res_task,5)];
                    
                }
                sqlite3_finalize(res_task);
            }
        }
        else
        {
            NSLog(@"Error: database could not be found in TaskDetailViewController");
        }
    }
    
    @catch (NSException *exception) {
        NSLog(@"An exception occured: %@", [exception reason]);
    }
    @finally {
        // close the database connection
        sqlite3_close(_database);
    }
    
    [self.tableView reloadData];
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark -
#pragma mark Table view data source methods

/*
 Standard table view data source and delegate methods to display a table view containing a single section with three rows showing different properties of the book.
 */

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // 1 section.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // 3 rows.
    return 4;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	static NSString *CellIdentifier = @"TaskFieldCell";
    /*
	 Dequeue or create and then configure a table cell for each attribute of the book.
	 */
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier];
		
        if(indexPath.row >= 2)
            cell.editingAccessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
    }
    
	switch (indexPath.row) {
        case 0:
            cell.textLabel.text = @"Activity";
			cell.detailTextLabel.text = _taskDetailModel[1];
			break;
        case 1:
            cell.textLabel.text = @"Category";
			cell.detailTextLabel.text = _taskDetailModel[2];
			break;
        case 2:
			cell.textLabel.text = @"Start Time";
			cell.detailTextLabel.text = _startTimeString;
			break;
        case 3:
			cell.textLabel.text = @"End Time";
			cell.detailTextLabel.text = _endTimeString;
			break;
        
    }
    return cell;
}


- (NSIndexPath *)tableView:(UITableView *)tv willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Only allow selection if editing.
    if(indexPath.row >= 2)
        return (self.editing) ? indexPath : nil;
    else
        return nil;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	
    // Only allow selection if editing.
	if (!self.editing) return;
	
	/*
	 Create, configure, and push the editing controller.
	 */
    TaskEditingViewController *controller = [[TaskEditingViewController alloc] init];
    
    controller.taskID = _taskID;
    controller.startTime = _startTime;
    controller.startTimeString = _startTimeString;
    controller.endTime = _endTime;
    controller.endTimeString = _endTimeString;
    
    controller.sourceController = self;
	
    switch (indexPath.row) {
        case 2: {
            controller.editedPropertyKey = @"Start Time";
            controller.editedPropertyDisplayName = NSLocalizedString(@"Start Time", @"Start Time");
        } break;
        case 3: {
            controller.editedPropertyKey = @"End Time";
			controller.editedPropertyDisplayName = NSLocalizedString(@"End Time", @"End Time");
        } break;
    }
	
    [self.navigationController pushViewController:controller animated:YES];
}


- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
	// Do not allow rows to be deleted when in editing mode.
	return UITableViewCellEditingStyleNone;
}


- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath {
	// Do not indent rows when in editing mode.
	return NO;
}


- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
	// create the parent view that will hold header Label
	UIView* customView = [[UIView alloc] initWithFrame:CGRectMake(10.0, 0.0, 310.0, 44.0)];
    
	// create the date screen title as button
    _deleteButton = [[UIButton alloc] initWithFrame:CGRectZero];
    _deleteButton.frame = CGRectMake(100.0, 3.0, 120.0, 41.0);
    _deleteButton.backgroundColor = [UIColor redColor];
    _deleteButton.layer.borderColor = [[UIColor redColor] CGColor];
    _deleteButton.layer.borderWidth = 1.0;
    [_deleteButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_deleteButton addTarget: self action: @selector(deleteClicked:) forControlEvents: UIControlEventTouchDown];
    [_deleteButton setTitle:@"Delete" forState:UIControlStateNormal];
  	[customView addSubview:_deleteButton];
    
	return customView;
}

- (CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
	return 44.0;
}

- (void) deleteClicked: (id)sender
{
    NSLog(@"delete clicked");
    
    
    // update database
    @try {
        
        // connect to db
        
        NSString *docsDir;
        NSArray *dirPaths;
        
        // Get the documents directory
        dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        
        docsDir = dirPaths[0];
        
        // Build the path to the database file
        _databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"TimeTracker.sqlite"]];
        
        NSLog(@"database path: %@",_databasePath);
        
        NSFileManager *filemgr = [NSFileManager defaultManager];
        
        // check to see if database already exists...
        if ([filemgr fileExistsAtPath: _databasePath ] == YES)
        {
            // open database
            if(!(sqlite3_open([_databasePath UTF8String], &_database) == SQLITE_OK))
            {
                NSLog(@"An error has occured when trying to open the database");
            }
            
            NSString *update_sql;
            
            
            update_sql = [NSString stringWithFormat:@"update tasklog set active = '0' where id like '%@'",_taskID];
            
            
            const char *update_const = [update_sql UTF8String];
            sqlite3_stmt *res_update;
            if(sqlite3_prepare(_database, update_const, -1, &res_update, NULL) != SQLITE_OK)
            {
                NSLog(@"Problem with prepare statement: %s",update_const);
                NSLog(@"%s Prepare failure '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(_database), sqlite3_errcode(_database));
            }
            else
            {
                NSLog(@"query: %s",update_const);
                if(SQLITE_DONE != sqlite3_step(res_update))
                    NSAssert1(0, @"Error while updating. '%s'", sqlite3_errmsg(_database));
                
                sqlite3_finalize(res_update);
            }
        }
        else
        {
            NSLog(@"Error: database could not be found in ActivityEditingViewController");
        }
    }
    @catch (NSException *exception) {
        NSLog(@"An exception occured: %@", [exception reason]);
    }
    @finally {
        // close the database connection
        sqlite3_close(_database);
    }

    
    // return to previous view
    [self.navigationController popViewControllerAnimated:YES];
}



- (void)viewDidUnload {
    [super viewDidUnload];
}
@end
